package org.grayrabbit.web.struts2.interceptor;

import org.grayrabbit.commons.util.logging.Logger;
import org.grayrabbit.commons.util.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * Write class comments here
 * <p/>
 * User: sys53
 * Date: 14-3-12 上午10:21
 * version $Id: TimerInterceptor.java, v 0.1 Exp $
 */
public class TimerInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -2790178429219647778L;
    private static final Logger LOGGER = LoggerFactory.getLogger(TimerInterceptor.class);

    @Value("${action.warn.time:3000}")
    private int warnTime = 3000;

    @Value("${action.error.time:5000}")
    private int errorTime = 5000;


    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        long startTime = System.currentTimeMillis();//计算开始日期
        String result = invocation.invoke();
        long executionTime = System.currentTimeMillis() - startTime;
        StringBuffer message = new StringBuffer(100);
        message.append("执行 action [");
        String namespace = invocation.getProxy().getNamespace();
        if ((namespace != null) && (namespace.trim().length() > 0)) {
            message.append(namespace).append("/");
        }
        message.append(invocation.getProxy().getActionName());
        message.append("!");
        message.append(invocation.getProxy().getMethod());
        message.append("] 花费了 ").append(executionTime).append(" ms.");
        if(executionTime>errorTime){
            LOGGER.error(message.toString());
        }else if(executionTime>warnTime){
            LOGGER.warn(message.toString());
        }else {
            LOGGER.info(message.toString());
        }
        return result;

    }
}
